package com.dynabook.ems.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dynabook.ems.mapper.RolesMapper;
import com.dynabook.ems.mapper.UsersMapper;
import com.dynabook.ems.model.entity.Roles;
import com.dynabook.ems.model.entity.Users;
import com.dynabook.ems.model.vo.UserRoleVO;
import com.dynabook.ems.service.RolesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
* @author tester
* @description 针对表【roles】的数据库操作Service实现
* @createDate 2025-07-30 16:25:33
*/
@Slf4j
@Service
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles>
    implements RolesService{

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserRoleVO getRoleByUserId(String userId) {
        if (userId == null) {
            return null;
        }
        
        // 根据用户ID查询用户信息获取role_id
        // 先查询总数以检测数据重复问题（只查询可用账户 active=1）
        LambdaQueryWrapper<Users> countWrapper = new LambdaQueryWrapper<Users>()
                .eq(Users::getNumber, userId)
                .eq(Users::getActive, 1);
        Long count = usersMapper.selectCount(countWrapper);
        
        if (count == null || count == 0) {
            return null;
        }
        
        // 如果存在多条记录，记录警告
        if (count > 1) {
            log.warn("发现用户ID({})存在多条可用账户记录({})，已自动选择第一条。建议检查数据库数据一致性！", userId, count);
        }
        
        // 使用selectList + last("LIMIT 1")来避免多条记录异常（只查询可用账户 active=1）
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<Users>()
                .eq(Users::getNumber, userId)
                .eq(Users::getActive, 1)
                .last("LIMIT 1");
        List<Users> userList = usersMapper.selectList(queryWrapper);
        
        if (userList == null || userList.isEmpty()) {
            return null;
        }
        
        Users user = userList.get(0);
        if (user.getRoleId() == null) {
            return null;
        }

        
        // 根据role_id查询角色信息
        Roles role = this.getById(user.getRoleId());
        if (role == null) {
            return null;
        }
        
        UserRoleVO userRoleVO = new UserRoleVO();
        userRoleVO.setDescription(role.getDescription());
        userRoleVO.setRoleId(role.getId());

        // 处理notes字段，去除HTML标签
        String notes = role.getNotes();
        if (StringUtils.hasText(notes)) {
            // 去除<p>标签
            notes = notes.replaceAll("</?p[^>]*>", "").trim();
            userRoleVO.setNotes(notes);
        } else {
            userRoleVO.setNotes(null);
        }
        
        return userRoleVO;
    }

}




